package org.come.Jpanel;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;

import cn.hutool.core.util.StrUtil;
import com.tool.role.RoleData;
import org.come.Frame.BoothBoxJframe;
import org.come.Frame.TradeJframe;
import org.come.Frame.ZhuFrame;
import org.come.entity.Goodstable;
import org.come.entity.RoleSummoning;
import org.come.mouslisten.ChoseGoodsStallMouslisten;
import org.come.until.EquipTool;
import org.come.until.FormsManagement;
import org.come.until.GoodsListFromServerUntil;
import org.come.until.UserMessUntil;

import com.tool.Document.NumberDocument;
import com.tool.Stall.Commodity;
import com.tool.Stall.Stall;
import com.tool.Stall.StallBean;
import com.tool.btn.BoothBoxBtn;
import com.tool.btn.FormsOnOffBtn;
import com.tool.tcpimg.UIUtils;
import com.updateNew.MyIsif;

 

public class BoothBoxJpanel extends JPanel {
    private Stall Stall;

    public Stall getStall2() {
        return Stall;
    }

    public Stall getStall() {
        if (Stall == null) {
            Stall = new Stall(RoleData.getRoleData().getLoginResult());
        }
        return Stall;
    }
    private String tw;
    // 要摆摊的对象
    private Commodity commodity;
    private JLabel labpettrade;// 放置选中要摆摊的图像
    private JTextField textUnitprice,// 放置出售的物品单价
            textNumber,TWname;// 放置出售的物品数量
    public JLabel[] GoodsListLabel = new JLabel[24];// 用来存放24个物品表格
    public String[] Usetime = new String[24];// 用来存放24个物品的数量
    public JLabel[] PetsListLabel = new JLabel[5];// 用来存放5个宠物表格
    private BoothBoxBtn btnTheshelves,// 上架
            btnshelves,// 下架
            btnStall;// 摆摊

    public BoothBoxJpanel(BoothBoxJframe boothBoxJframe) throws Exception {
        	this.setPreferredSize(new Dimension(619, 430));
            this.setLayout(null);
            this.setOpaque(false);
            // 关闭按钮事件
            FormsOnOffBtn offBtn = new FormsOnOffBtn("inkImg/old/2/1.png", 1, 16);
            offBtn.setBounds(619 - 37, 10, 25, 25);
            this.add(offBtn);
            // 放置选中要交易的宠物头像
            labpettrade = new JLabel("", SwingConstants.CENTER);
            labpettrade.setBounds(478, 83, 66, 66);
            this.add(labpettrade);
            // 放置出售的物品单价
            textUnitprice = new JTextField();
            textUnitprice.setBounds(478, 188, 110, 16);
            textUnitprice.setText("0");
            textUnitprice.setOpaque(false);
            textUnitprice.setForeground(Color.WHITE);
            textUnitprice.setCaretColor(Color.WHITE);
            textUnitprice.setBorder(BorderFactory.createEmptyBorder());
            textUnitprice.setDocument(new NumberDocument(textUnitprice));
            this.add(textUnitprice);
            // 放置出售的物品数量
            textNumber = new JTextField();
            textNumber.setBounds(478, 150, 65, 16);
            textNumber.setText("0");
            textNumber.setOpaque(false);
            textNumber.setCaretColor(Color.WHITE);
            textNumber.setForeground(Color.WHITE);
            textNumber.setBorder(BorderFactory.createEmptyBorder());
            textNumber.addKeyListener(new KeyListener() {
                // 键盘监听
                @Override
                public void keyTyped(KeyEvent e) {
                    int keyChar = e.getKeyChar();
                    // 让该输入框只能输入数字
                    if (keyChar < KeyEvent.VK_0 || keyChar > KeyEvent.VK_9 || commodity == null) {
                        e.consume();
                        return;
                    }
                    if (commodity.getGood() != null) {
                        String key = textNumber.getText();
                        String value = getLimit(key, commodity.getGood().getUsetime()); // 该框只能输入这个物品的最大数量
                        if (value.indexOf(e.getKeyChar()) < 0) {
                            e.consume();
                        }
                    } else {
                        e.consume();
                    }
                }

                @Override
                public void keyReleased(KeyEvent e) {
                    if (commodity != null) {
                        Goodstable good = commodity.getGood();
                        RoleSummoning pet = commodity.getPet();
                        if (good != null) {
                            String str = textNumber.getText();
                            if (str.length() > 0) {
                                // 当首字母为0时，则自动取得
                                if (str.charAt(0) == '0') {
                                    textNumber.setText(Integer.valueOf(str).toString());
                                }
                                // 如果输入的数量大于该物品的数量时，则只能显示最大数量
                                if (Integer.parseInt(str) >= good.getUsetime()) {
                                    textNumber.setText(good.getUsetime().toString());
                                }
                            }
                        } else if (pet != null) {
                            textNumber.setText(1 + "");
                        } else {
                            textNumber.setText(0 + "");
                        }
                    }
                }

                @Override
                public void keyPressed(KeyEvent e) {
                    // TODO Auto-generated method stub

                }
            });
            this.add(textNumber);
            int Flag = 0;
            int count = 1;
            // 存放物品的表格1~24
            for (int i = 0; i < 24; i++) {
                Flag = i % 6;
                count = i / 6;
                GoodsListLabel[i] = new JLabel();
                GoodsListLabel[i].addMouseListener(new ChoseGoodsStallMouslisten(i, 0, this));
                GoodsListLabel[i].setBounds(73 + Flag * 51, 92 + 51 * count, 48, 48);
                this.add(GoodsListLabel[i]);
            }
            // 存放宠物头像的五个表格框
            for (int j = 0; j < 5; j++) {
                PetsListLabel[j] = new JLabel();
                PetsListLabel[j].addMouseListener(new ChoseGoodsStallMouslisten(j, 1, this));
                PetsListLabel[j].setBounds(73 + j * 63, 352, 51, 51);
                this.add(PetsListLabel[j]);
            }
            
            //摊位名字
        	TWname = new JTextField();// 
        	TWname.setBorder(BorderFactory.createEmptyBorder());
        	TWname.setForeground(Color.white);
        	TWname.setCaretColor(Color.white);
        	TWname.setFont(new Font("宋体",Font.PLAIN,15));
        	TWname.setBounds(455, 27, 105, 16);
        	TWname.setText("");
        	TWname.setOpaque(false);
        	
        	TWname.addKeyListener(new KeyListener() {
        		// 键盘监听
        		@Override
        		public void keyTyped(KeyEvent e) {
//                tw = TWname.getText();
        		}
        		
        		@Override
        		public void keyReleased(KeyEvent e) {
        			if(TWname.getText().length()>6) {
        				TWname.setText(TWname.getText().substring(0,6));
        			}
        			tw = TWname.getText();
        		}
        		
        		@Override
        		public void keyPressed(KeyEvent e) {
        			// TODO Auto-generated method stub
        			
        		}
        	});
        	this.add(TWname);
            // 上架
            btnTheshelves = new BoothBoxBtn("skin/8100226/newbutton/B20.png", 1, UIUtils.COLOR_BLACK, "上架", this);
            btnTheshelves.setBounds(445, 220, 59, 24);
            this.add(btnTheshelves);
            // 下架
            btnshelves = new BoothBoxBtn("skin/8100226/newbutton/B20.png", 1, UIUtils.COLOR_BLACK, "下架", this);
            btnshelves.setBounds(525, 220, 59, 24);
            this.add(btnshelves);
            // 摆摊收摊按钮
            btnStall = new BoothBoxBtn("skin/8100226/newbutton/B20.png", 1, UIUtils.COLOR_BLACK, "摆摊", this);
            btnStall.setBounds(485, 360, 59, 24);
            this.add(btnStall);

    }

    private ImageIcon icon;
    int row;
    int col;


    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        	if (icon == null) {
                icon = new ImageIcon("inkImg/newbackground/B250.png");
            }
            g.drawImage(icon.getImage(), 0, 0, 619, 430, this);
            g.setColor(Color.white);
            g.setFont(UIUtils.TEXT_MSG);
            for (int i = 0; i < Usetime.length; i++) {
                String s = Usetime[i];
                if(StrUtil.isBlank(s)){
                    continue;
                }
                row = i % 6;
                col = i / 6;
                // 判断如果数量值不为空
                if (Usetime[i] != null) {
                    g.drawString(Usetime[i], 73 + row * 51, 92+13 + col * 51);
                }
            }
    }

    // 选中一个物品或者一个召唤兽
    public void XZBuy(Goodstable good, RoleSummoning pet) {
    		if (good != null) {
                commodity = new Commodity();
                // commodity.setGood((Goodstable)good.clone());
                commodity.setGood(good);
                commodity.setMoney(1);
                commodity.setCurrency("金钱");
                textUnitprice.setText("1");// 放置出售的物品单价
                textNumber.setText("1");// 放置出售的物品数量
                ImageIcon img = GoodsListFromServerUntil.imgpathAdaptive(good.getSkin(),49,49);
                labpettrade.setIcon(img);
            } else if (pet != null) {
                commodity = new Commodity();
                commodity.setPet(pet);
                commodity.setMoney(1);
                commodity.setCurrency("金钱");
                textUnitprice.setText("1");// 放置出售的物品单价
                textNumber.setText("1");// 放置出售的物品数量
                ImageIcon img = new ImageIcon("inkImg/hongmu/2/101_png.xy2uiimg.pet_def.png");
                img.setImage(img.getImage().getScaledInstance(55, 55, 10));
                labpettrade.setIcon(img);
            }
    }

    // 初始化
    public void init(Stall stall2) {
        this.Stall = stall2;
        // 记录摊位的物品信息 24
        Commodity[] goodstables = Stall.getGoodstables();
        for (int i = 0; i < goodstables.length; i++) {
            Commodity com = goodstables[i];
            if (com == null) {
                GoodsListLabel[i].setIcon(null);
                Usetime[i] = null;
            } else {
                ImageIcon img = GoodsListFromServerUntil.imgpathAdaptive(com.getGood().getSkin(),49,49);
                GoodsListLabel[i].setIcon(img);
                if (!EquipTool.isEquip(com.getGood().getType())) {
                    Usetime[i] = com.getGood().getUsetime() + "";
                }
            }
        }
        // 记录摆摊的召唤兽
        Commodity[] pets = Stall.getPets();
        for (int i = 0; i < pets.length; i++) {
            Commodity com = pets[i];
            if(PetsListLabel!=null && i<5){
                if (com == null) {
                    PetsListLabel[i].setIcon(null);
                } else {
                    ImageIcon img = new ImageIcon("inkImg/hongmu/2/101_png.xy2uiimg.pet_def.png");
                    img.setImage(img.getImage().getScaledInstance(49, 49, 10));
                    PetsListLabel[i].setIcon(img);
                }
            }
        }
    }

    // id更改
    public void CId(StallBean bean) {
        if (Stall == null) {
            Stall = new Stall(RoleData.getRoleData().getLoginResult());
        }
        Stall.setId(bean.getId());
        Stall.setState(bean.getState());
        if (bean.getState() == StallBean.NO) {
            Stall.setId(0);
            for (int i = 0; i < 24; i++) {
                Stall.getGoodstables()[i] = null;
                GoodsListLabel[i].setIcon(null);
                Usetime[i] = null;
            }
            // 存放宠物头像的五个表格框
            for (int j = 0; j < 5; j++) {
                Stall.getPets()[j] = null;
                PetsListLabel[j].setIcon(null);
            }
            this.commodity = null;
            labpettrade.setIcon(null);
            textUnitprice.setText("0");// 放置出售的物品单价
            textNumber.setText("0");// 放置出售的物品数量
            FormsManagement.HideForm(15);
            FormsManagement.HideForm(16);
        }
    }

    // 修改界面
    public void shuaxing(Stall stall) {
        // 记录摊位的物品信息 24
        Commodity[] goodstables = stall.getGoodstables();
        for (int i = 0; i < goodstables.length; i++) {
            Commodity com = goodstables[i];
            if (com == null) {
                getStall().getGoodstables()[i] = null;
                GoodsListLabel[i].setIcon(null);
                Usetime[i] = null;
            } else {
                getStall().getGoodstables()[i].setGood(com.getGood());
                if (!EquipTool.isEquip(com.getGood().getType())) {
                    Usetime[i] = com.getGood().getUsetime() + "";
                }
            }
        }
        // 记录摆摊的召唤兽
        Commodity[] pets = stall.getPets();
        for (int i = 0; i < pets.length; i++) {
            Commodity com = pets[i];
            if (com == null) {
                getStall().getPets()[i] = null;
                PetsListLabel[i].setIcon(null);
            } else {
                getStall().getPets()[i].setPet(com.getPet());
            }
        }
    }

    // 将添加的到指定格子
    public void SJ() {
        if (commodity == null) {
            ZhuFrame.getZhuJpanel().addPrompt2("没有选中的商品");
            return;
        }
        if (getStall().ysj(commodity)) {
            ZhuFrame.getZhuJpanel().addPrompt2("不能重复上架");
            return;
        }
        Goodstable good = commodity.getGood();
        RoleSummoning pet = commodity.getPet();
        int sum = Integer.parseInt(textNumber.getText());
        long money = Long.parseLong(textUnitprice.getText().replaceAll(",", ""));
        if (sum <= 0) {
            ZhuFrame.getZhuJpanel().addPrompt2("最少也的卖一个吧");
            return;
        }
        if (money <= 0) {
            ZhuFrame.getZhuJpanel().addPrompt2("金额需要大于0");
            return;
        }
        commodity.setMoney(money);
        if (good != null) {
            if (GoodsListFromServerUntil.isExist(good)) {
                return;
            }
            good = (Goodstable) good.clone();
            commodity.setGood(good);
            if (sum > good.getUsetime()) {
                ZhuFrame.getZhuJpanel().addPrompt2("数量不足");
                return;
            }
            good.setUsetime(sum);
            Commodity[] goods = getStall().getGoodstables();
            // 判断商品是否重叠
            if (EquipTool.isEquip(good.getType())) {// 不可重叠
                for (int i = 0; i < goods.length; i++) {
                    Commodity com = goods[i];
                    if (com == null) {
                        commodity.setGood(good);
                        goods[i] = commodity;
                        GoodsListLabel[i].setIcon(labpettrade.getIcon());
                        GoodsListFromServerUntil.stall1(good);
                        Usetime[i] = null;
                        XZBuy(null);
                        return;
                    }
                }
                ZhuFrame.getZhuJpanel().addPrompt2("最多上架24个物品");
            } else {// 重叠
                int p = -1;
                for (int i = 0; i < goods.length; i++) {
                    Commodity com = goods[i];
                    if (com != null) {
                        Goodstable good2 = com.getGood();
                        if (good2.getGoodsid().compareTo(good.getGoodsid()) == 0
                                && com.getMoney() == commodity.getMoney()) {
                            good2.setUsetime(good2.getUsetime() + good.getUsetime());
                            GoodsListFromServerUntil.stall1(good);
                            Usetime[i] = good2.getUsetime() + "";
                            XZBuy(null);
                            return;
                        }
                    } else {
                        if (p == -1) {
                            p = i;
                        }
                    }
                }
                if (p == -1) {
                    ZhuFrame.getZhuJpanel().addPrompt2("最多上架24个物品");
                } else {
                    commodity.setGood(good);
                    goods[p] = commodity;
                    GoodsListLabel[p].setIcon(labpettrade.getIcon());
                    GoodsListFromServerUntil.stall1(good);
                    Usetime[p] = good.getUsetime() + "";
                    XZBuy(null);
                    return;
                }
            }
        } else if (pet != null) {
            Commodity[] pets = getStall().getPets();
            for (int i = 0; i < pets.length; i++) {
                Commodity com = pets[i];
                if (com == null) {
                    // 需要补充
                    // 则将这个宠物移除
                    int p = -1;
                    for (int j = UserMessUntil.getPetListTable().size() - 1; j >= 0; j--) {
                        if (UserMessUntil.getPetListTable().get(j).getSid().compareTo(pet.getSid()) == 0) {
                            UserMessUntil.getPetListTable().remove(j);
                            p = j;
                            break;
                        }
                    }
                    if (p == -1) {
                        ZhuFrame.getZhuJpanel().addPrompt2("宝宝去哪了");
                        return;
                    }
                    TradeJframe.getTradejframe().getTradejpanel().getModelname().remove(p);
                    commodity.setPet(pet);
                    pets[i] = commodity;
                    PetsListLabel[i].setIcon(labpettrade.getIcon());
                    XZBuy(null);
                    return;
                }
            }
            ZhuFrame.getZhuJpanel().addPrompt2("最多上架5只召唤兽");
        }
    }

    // 选中商品
    public void XZBuy(Commodity commodity) {
        if (commodity == null) {
            this.commodity = null;
            labpettrade.setIcon(null);
            textUnitprice.setText("0");// 放置出售的物品单价
            textNumber.setText("0");// 放置出售的物品数量
        } else {
            this.commodity = commodity;
            ((NumberDocument) textUnitprice.getDocument()).replace(commodity.getMoney() + "");
            // textUnitprice.setText(commodity.getMoney()+"");//放置出售的物品单价
            Goodstable good = commodity.getGood();
            RoleSummoning pet = commodity.getPet();
            if (good != null) {
                ImageIcon img = GoodsListFromServerUntil.imgpathAdaptive(good.getSkin(),49,49);
                labpettrade.setIcon(img);
                textNumber.setText(good.getUsetime() + "");
            } else if (pet != null) {
                ImageIcon img = new ImageIcon("inkImg/hongmu/2/101_png.xy2uiimg.pet_def.png");
                img.setImage(img.getImage().getScaledInstance(49, 49, 10));
                labpettrade.setIcon(img);
                textNumber.setText("1");
            }
        }
    }

    // 群体下架
    public void QXJ() {
        if (getStall().getId() > 0) {
            return;
        }
        for (int i = 0; i < getStall().getGoodstables().length; i++) {
            if (getStall().getGoodstables()[i] != null) {
                XZBuy(getStall().getGoodstables()[i]);
                btnshelves.nochoose(null);
            }
        }
        for (int i = 0; i < getStall().getPets().length; i++) {
            if (getStall().getPets()[i] != null) {
                XZBuy(getStall().getPets()[i]);
                btnshelves.nochoose(null);
            }
        }
    }

    public JLabel getLabpettrade() {
        return labpettrade;
    }

    public void setLabpettrade(JLabel labpettrade) {
        this.labpettrade = labpettrade;
    }

    public JTextField getTextNumber() {
        return textNumber;
    }

    public void setTextNumber(JTextField textNumber) {
        this.textNumber = textNumber;
    }

    public JLabel[] getGoodsListLabel() {
        return GoodsListLabel;
    }

    public void setGoodsListLabel(JLabel[] goodsListLabel) {
        GoodsListLabel = goodsListLabel;
    }

    public JLabel[] getPetsListLabel() {
        return PetsListLabel;
    }

    public void setPetsListLabel(JLabel[] petsListLabel) {
        PetsListLabel = petsListLabel;
    }

    private String getLimit(String key, int num) {
        // 示例讲解：key = "13" count = 135
        String value = String.valueOf(num); // value = "135";
        int a[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, b = num;
        // b = 135,a[] = {0,……};
        int len = key.length(), length = value.length();
        // len = 2,length = 3;
        for (int i = 0; b > 0; i++, b /= 10) {
            a[length - 1 - i] = b % 10;
        }
        // a[] = {1,3,5,0,……};
        int in;
        if ("".equals(key)) {
            in = 0;
        } else {
            in = Integer.valueOf(key) * 10;
        }
        // in = 130;
        if (len < length - 1) {
            if (len == 0) {
                value = string(1, 9); // 限制第一位不能输入0
            } else {
                value = string(0, 9);
            }
        } else if (len == length - 1) {
            // 进入这里 in = 130 < num = 135
            if (in <= num) {
                if (in == 0) {
                    value = string(1, a[len]);
                } else {
                    value = string(0, a[len]); // 所以：value = "012345";
                }
            } else {
                value = "";
            }
        } else {
            value = "";
        }
        // 返回的字符串为："0123456"
        return value;
    }

    private static String string(int a, int b) {
        String value = "";
        for (int i = a; i <= b; i++) {
            value += String.valueOf(i);
        }
        return value;
    }

    public Commodity getCommodity() {
        return commodity;
    }

    public void setCommodity(Commodity commodity) {
        this.commodity = commodity;
    }

    public BoothBoxBtn getBtnTheshelves() {
        return btnTheshelves;
    }

    public void setBtnTheshelves(BoothBoxBtn btnTheshelves) {
        this.btnTheshelves = btnTheshelves;
    }

    public BoothBoxBtn getBtnshelves() {
        return btnshelves;
    }

    public void setBtnshelves(BoothBoxBtn btnshelves) {
        this.btnshelves = btnshelves;
    }

    public BoothBoxBtn getBtnStall() {
        return btnStall;
    }

    public void setBtnStall(BoothBoxBtn btnStall) {
        this.btnStall = btnStall;
    }


	public String getTw() {
		return tw;
	}

	public void setTw(String tw) {
		this.tw = tw;
	}


}
